import express from "express";
import cors from "cors";
import routes from "./routes";
import { fail } from "./utils/response";
import { errorHandler } from "./middleware/error.handler";
import session from "express-session";

const app = express();

// app.use(cors());
app.use(
  cors({
    origin: "http://localhost:5173",
    credentials: true,
  })
);
app.use(express.json());
app.use(
  session({
    secret: process.env.SESSION_SECRET || "wx_123456",
    resave: false,
    saveUninitialized: false,
    cookie: {
      secure: process.env.NODE_ENV === "production", // 生产环境需开启HTTPS
      maxAge: 24 * 60 * 60 * 1000, // 1天有效期
    },
  })
);

app.use("/api", routes);

// 404
app.use((req, res) => fail(res, 404, "接口不存在"));
// error handler
app.use(errorHandler);

export default app;
